using System.Runtime.CompilerServices;

namespace System.Utility
{
	public abstract class AbstractSyncResult : IAsyncResult
	{
		private bool _IsCompleted;

		private string _Message;

		private double _Total;

		private double _Completed;

		private string _Log;

		public virtual double Completed
		{
			get
			{
				return _Completed;
			}
		}

		public virtual bool IsCompleted
		{
			get
			{
				return _IsCompleted;
			}
		}

		public virtual bool IsSuccess
		{
			get;
			set;
		}

		public string Log
		{
			get
			{
				return _Log;
			}
			set
			{
				_Log = value;
			}
		}

		public virtual string Message
		{
			get
			{
				return _Message;
			}
			set
			{
				_Message = value;
			}
		}

		public AdvanceEventHandler OnAdvance
		{
			get;
			set;
		}

		public Action OnCompleted
		{
			get;
			set;
		}

		public virtual double Percent
		{
			get
			{
				return (Total > 0 ? Completed * 100 / Total : 0);
			}
		}

		public virtual double Total
		{
			get
			{
				return _Total;
			}
		}

		public AbstractSyncResult()
		{
			_Completed = 0;
			_Total = 0;
			_IsCompleted = false;
			IsSuccess = true;
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		public virtual void Advance(double work, string message = "", object sender = null)
		{
			_Completed += work;
			_Message = message;
			if ((OnAdvance == null ? false : !_IsCompleted))
			{
				OnAdvance(work, message);
			}
			if ((_Completed < _Total ? false : !IsCompleted))
			{
				_Completed = _Total;
				_IsCompleted = true;
				if (OnCompleted != null)
				{
					OnCompleted();
				}
			}
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		public void AdvanceCompleted(double completed, string message = "")
		{
			_Completed = completed;
			_Message = message;
			if ((OnAdvance == null ? false : !_IsCompleted))
			{
				OnAdvance(0, message);
			}
			if ((_Completed < _Total ? false : !IsCompleted))
			{
				_Completed = _Total;
				_IsCompleted = true;
				if (OnCompleted != null)
				{
					OnCompleted();
				}
			}
		}

		public virtual void Start(double total)
		{
			_Total = total;
			_IsCompleted = false;
			_Completed = 0;
			IsSuccess = true;
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		public virtual void Stop()
		{
			if (!IsCompleted)
			{
				_IsCompleted = true;
				if (OnCompleted != null)
				{
					OnCompleted();
				}
			}
		}

		public void WriteMessage(string mes)
		{
			_Message = mes;
			if (OnAdvance != null)
			{
				OnAdvance(0, mes);
			}
		}
	}
}